define([
    'require',
    'angular',
    'underscore'
], function (require, angular, _) {
    return function ($rootScope, $scope, $routeParams, $http, RuleSerivce, Resource,$compile, $timeout, GillionMsg,RuleEditService) {
        RuleSerivce.readyData();
        RuleSerivce.setVariableScope(4);
        $rootScope.headerPackageId=$routeParams.packageId;
        RuleSerivce.promises().then(function () {
            $scope.status=$rootScope.currPackage.status;
            $scope.businessModelId=$scope.currPackage.businessModelId;
            //加载模型
            Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
                id:  $scope.businessModelId
            }, function (response) {
                if(response.data!=null){
                    $scope.modelAttributes=response.data;
                }
            });

            var resp = $rootScope.currDecisionTable;
            $scope.assemblyName = resp.name;
            if(resp.conditions!=null&&resp.conditions!="undefined"&&resp.conditions!="{}") {
                $scope.context = resp.conditions;
                var json = eval('(' + $scope.context + ')');
                var resultList = RuleEditService.showRule(json);
                RuleEditService.setHtml($scope,resultList,"condition");
            }else{
                RuleEditService.addConditionRow($scope,"","",true);//首行无需添加并且或者
            }
        });
        angular.element('.engine-tab li:first').trigger('click');
        $scope.packageId = $routeParams.packageId;
        $scope.projectId = $routeParams.projectId;
        RuleSerivce.getRulePackageMenu($scope.packageId);
        Resource("/grule-manager/projects/"+$scope.projectId).get({},function(project){
            $scope.currProjcet = project;
        });
        $scope.tableId = $routeParams.tableId;
        $scope.select = function(menu){
            if(menu.decisionTable){
                RuleSerivce.setCurrentDecisionTable(menu);
                RuleSerivce.setVariableScope(4);
            }
            else{
                RuleSerivce.setCurrentAssembly(menu);
                RuleSerivce.setVariableScope(2);
            }
        };
        $scope.selectRule = function(rule){
            $http({
                url:"/grule-manager/ruleAssembly/"+rule.ruleAssemblyId,
                method:"GET",
                params:{
                    id:rule.ruleAssemblyId
                }
            }).success(function(resp){
                RuleSerivce.setCurrentAssembly(resp);
            })
            RuleSerivce.setCurrentRule(rule);
            RuleSerivce.setVariableScope(3);
        };

        $scope.count=1;
        $scope.countCondition=1;
        $scope.nowClick = 1;
        $scope.jsonContext={};
        $scope.showSign=false;
        $scope.showProperty=false;
        $scope.showEntry=false;
        $scope.showNone=true;
        $scope.showAllCondition=false;
        $scope.showMethod=false;
        $scope.id=$routeParams.tableId;
        $scope.translate=[{">":"大于"},{">=":"大于等于"},{"==":"等于"},{"<":"小于"},{"<=":"小于等于"},{"!=":"不等于"},{"+":"加"},
            {"-":"减"},{"*":"乘"},{"/":"除"},{"(":"("},{")":")"}];
        $scope.conditionRows=[];
        $scope.conditions=[];
        var ruleAssemblyResource = Resource("/grule-manager/decision-tables/:id", {
            id: "@id"
        });
        $scope.createRule=function(){
            GillionMsg.showUrl({
                title: '新建规则',
                url: '/html2/rule/create/createRule',
                width: 400,
                height: 300,
                data: $scope.id,
                onClose: function (data) {
                    if (data.success) {
                        GillionMsg.alert("提示", "规则新建成功");
                        RuleSerivce.getRulePackageMenu($scope.packageId);
                    }
                }
            });
        };
        $scope.select = function(menu){
            if(menu.decisionTable){
                RuleSerivce.setCurrentDecisionTable(menu);
                RuleSerivce.setVariableScope(4);
            }
            else{
                RuleSerivce.setCurrentAssembly(menu);
                RuleSerivce.setVariableScope(2);
            }
        };
        $scope.selectRule = function(rule){
            RuleSerivce.setCurrentRule(rule);
            RuleSerivce.setVariableScope(3);
        };

        //加载模型
        Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
            id:  $scope.businessModelId
        }, function (response) {
            if(response.data!=null){
                $scope.modelAttributes=response.data;
            }
        });
        Resource("/grule-manager/data_dict/rule/dict/:id",{id: '@id'}).get({ id:  $rootScope.currProjcet.id}, function (response) {
            if(response.data!=null){
                $scope.dicts=response.data;
            }
        });
        //加载变量
        function loadVariables() {
            Resource("/grule-manager/variables/decisionTable/:id", {id: '@id'}).get({
                id: $routeParams.tableId
            }, function (response) {
                if(response.data!=null){
                    $scope.variables=response.data;
                }
            });
        }
        loadVariables();

        angular.element(document).off('refresh.variables').on('refresh.variables', function() {
            loadVariables();
        });

        //isButton 是否需要显示按钮
        $scope.addConditionRow=function(type,conditionList,isButton){
            RuleEditService.addConditionRow($scope,type,conditionList,isButton);
        };

        $scope.change=function (click){
            RuleEditService.change($scope,click);
        };
        
        $scope.selectLogicalSign=function(sign,mes,num){
            $scope.count++;
            var node   = angular.element("#symbol" + num).parent().empty();
            node.append(
                $compile(
                    "<a href='javascript:void(0)' ng-click='change("+$scope.count+")' name='node'  id='symbol"+$scope.count+"' value='{&apos;oper&apos;:&apos;"+sign+"&apos;}'>"+mes+"<i class='icon-engine-down-a'></i></a>"
                )($scope)
            )
        };

        $scope.removeCondition = function(num){
            angular.element("#click" + num).remove();
        };

        $scope.removeRowCondition=function(index){
            $scope.conditionRows.splice(index, 1);
        };

        $scope.copyCRow=function(index){
            RuleEditService.copyCRow($scope,index);
        };

        $scope.addRowCondition=function(index){
            RuleEditService.addRowCondition($scope,index);
        };

        $scope.show=function(type,model,showType){
            RuleEditService.show($scope,type,model,showType);
        };

        $scope.viewObject = function (id,margin) {
            RuleEditService.viewObject($scope,id,margin)
        };


        $scope.addButton= function(){
            RuleEditService.addButton($scope);
        }

        $scope.addEntry=function(){
            RuleEditService.addEntry($scope);
        };

        $scope.addDict=function(item){
            RuleEditService.addDict($scope,item);
        };

        $scope.addSign=function(value){
            RuleEditService.addSign($scope,value);
        };
        $scope.addModel=function(value){
            RuleEditService.addModel($scope,value);
        };

        $scope.addVariable=function(value){
            RuleEditService.addVariable($scope,value);
        };

        $scope.addMethod=function(value,text){
            RuleEditService.addMethod($scope,value,text);
        };

        $scope.addFront=function(value){
            RuleEditService.addFront($scope,value);
        };

        $scope.addBehind=function(value){
            RuleEditService.addBehind($scope,value);
        };

        $scope.save=function(){
            var list=[];
            var nodes = $("a[name='node']");
            if(nodes.length==0){
                GillionMsg.alert("提示","请编辑规则！");
                return;
            }
            angular.forEach(nodes,function(node){
                list.push( eval("(" + node.attributes.value.nodeValue + ")"));
            });
            var result = RuleEditService.getCondition(list);;
            var decisionTable={};
            decisionTable.id= $routeParams.tableId;
            decisionTable.conditions= JSON.stringify(result);
            if(decisionTable.conditions==null||decisionTable.conditions==undefined){
                decisionTable.conditions="{}";
            }
            ruleAssemblyResource.update(decisionTable, function (response) {
                if(response.success){
                    GillionMsg.alert("提示","修改成功！");
                }
            });
        };

        $scope.deleteMenu=function(menu){
            var path = 'ruleAssembly';
            if (menu.decisionTable) {
                path = 'decision-tables';
            }

            GillionMsg.confirm('提示信息', '是否确定删除？',
                function (r) {
                    if(r==true) {
                        Resource("/grule-manager/" + path + "/:id", {
                            id: "@id"
                        }).delete({
                            id: menu.id
                        }, function (response) {
                            if (response.success) {
                                GillionMsg.alert('提示', '删除成功', function(){
                                    angular.element(document).trigger('refresh.menu');
                                    window.location.href='/html2/home#/projects/' + $scope.projectId + '/packages/' +  $scope.packageId;
                                });
                            }
                        });
                    }
                }
            );
        };

        $scope.deleteRule=function(id){
            GillionMsg.confirm('提示信息', '是否确定删除？',
                function (r) {
                    if (r == true) {
                        Resource("/grule-manager/rule/:id", {
                            id: "@id"
                        }).delete({
                            id: id
                        }, function (response) {
                            if(response.success){
                                GillionMsg.alert('提示', '删除成功', function(){
                                    angular.element(document).trigger('refresh.menu');
                                    window.location.href='/html2/home#/projects/' + $scope.projectId + '/packages/' +  $scope.packageId;
                                });
                            }
                        });
                    }
                }
            )
        };

        
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.showEdit=function(type){
            RuleEditService.showEdit($scope,type);
        };
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.closeEdit=function(type,state){
            RuleEditService.closeEdit(type,state);
        };
        //添加括号方法
        $scope.addBracket=function(num){
            var nodesList=[];
            //$("#bracket").css("display", "block");
            var  rowNodes =$("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (nodesList[i].attributes.type.nodeValue == "property" || nodesList[i].attributes.type.nodeValue == "variable" || nodesList[i].attributes.type.nodeValue == "entry") {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + nodesList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='left' name ='leftBracket'><a href='javascript:void(0)' ng-click='addLeftBracket(&apos;" + nodesList[i].id + "&apos;)'>(</a></div>"
                            )($scope)
                        )
                    }
                }
            }
            showLeftBracket();
        };

        //点击左括号之后显示右括号
        function showRightBracket(nodeId){
            var nodesList=[];
            var startList=[];
            var  rowNodes= $("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].id==nodeId){
                    startList=nodesList.slice(i,nodesList.length);
                    break;
                }
            }
            for(var i=0;i<startList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (startList[i].attributes.type!=undefined&&(startList[i].attributes.type.nodeValue == "property" || startList[i].attributes.type.nodeValue == "variable" || startList[i].attributes.type.nodeValue == "entry")) {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + startList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='right' name ='rightBracket'><a href='javascript:void(0)' ng-click='addRightBracket(&apos;" + startList[i].id + "&apos;)'>)</a></div>"
                            )($scope)
                        )
                    }
                }
            }
        }

        //添加左括号
        $scope.addLeftBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.before(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;(&apos;}'>(</a></span>"
                )($scope)
            );

            cleanBracket("left");
            showRightBracket(nodeId);
        };

        //添加右边括号
        $scope.addRightBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.after(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;)&apos;}'>)</a></span>"
                )($scope)
            );

            cleanBracket("right");
            closeDiv();
        };

        function showLeftBracket(){
            $("#shadeCondition").css({ display: "block"});
            $("#bracket").css("display", "block");
        }

        function showDIV() {
            $("#shadeCondition").css({ display: "block"});
        }
        function closeDiv() {
            $("#shadeCondition").css({ display: "none"});
        }

        //type: left | right | all
        function cleanBracket(type){
            if(type=="left"||type=="all"){
                var  bracketNodes= $("[name='leftBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
            if(type=="right"||type=="all"){
                var  bracketNodes= $("[name='rightBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
        }
        //点击遮罩还原
        $("#shadeCondition").mouseup(function(){
            RuleEditService.init();
            closeDiv();
            cleanBracket("all");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).html("点击选择");
        });
        
    };
});